package com.yang.demo.controller;

import com.yang.demo.entity.Admin;
import com.yang.demo.entity.RespBean;
import com.yang.demo.entity.vo.AdminLoginVO;
import com.yang.demo.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Api(tags = "登录接口")
@RestController
@Slf4j
public class LoginController {
    @Autowired
    private IAdminService adminService;

    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("注销成功!");
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/admin/info")   //通过principal获取用户对象
    public Admin getAdminInfo(Principal principal) {
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null);
        admin.setRoles(adminService.getRolesByAdminId(admin.getId()));
        log.info("{}", principal);
        return admin;
    }

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginVO adminLoginVO, HttpServletRequest request) {

        return adminService.login(adminLoginVO.getUsername(), adminLoginVO.getPassword(), adminLoginVO.getCode(), request);
    }
}
